from django.shortcuts import render,HttpResponse
import random,string
from PIL import Image,ImageDraw,ImageFont,ImageFilter

def getRandomChar():
    ran = string.ascii_lowercase + string.digits
    char = ''.join(random.choices(ran,k=4))
    print('获得的随机数为：',char)
    return char

def getRandomColor():
    return (random.randint(50,150),random.randint(50,150),random.randint(50,150))

def create_code():
    img = Image.new('RGB',(120,30),(255,255,255))       #创建图片#取色样式，坐标，北京白色
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype('arial.ttf',25)
    code = getRandomChar()

    for t in range(4):
        print(code[t])
        draw.text((30*t+5,0),code[t],getRandomColor(),font)

    for _ in range(random.randint(0,50)):
        draw.point((random.randint(0,120),random.randint(0,120)),fill=getRandomColor())

    img = img.filter(ImageFilter.BLUR)
    # img.save(''.join(code) + '.jpg','jpeg')
    return img,code

from io import BytesIO

def create_code_img(request):

    f = BytesIO()
    img,code = create_code()
    request.session['check_code'] = code
    img.save(f,'jpeg')
    return HttpResponse(f.getvalue())

# Create your views here.
def index(request):
    return render(request,'index.html')